package com.puzzlebazar.client.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import com.google.gwt.user.client.Element;

public class GWTUtil {

	/**
	 * Disables the browsers default context menu for the specified element.
	 *
	 * @param elem the element whos context menu will be disabled
	 */
	public static native void disableContextMenu(Element elem) /*-{
	     elem.oncontextmenu=function() {  return false};
    }-*/; 


	/**
	 * get historyToken parameters
	 * 
	 * like domaint.tld#anchor?[var=1&var3=2&var3=3]
	 * 
	 * @param historyToken anchor tag
	 * @return hashmap of the parameters
	 */
	public static HashMap<String,String> getHistoryTokenParameters(String historyToken) {

		//skip if there is no question mark
		if (!historyToken.contains("?")) {
			return null;
		}

		// ? position
		int questionMarkIndex = historyToken.indexOf("?") + 1;

		//get the sub string of parameters var=1&var2=2&var3=3...
		String[] arStr = historyToken.substring(questionMarkIndex, historyToken.length()).split("&");
		final HashMap<String,String> params = new HashMap<String,String>();
		for (int i = 0; i < arStr.length; i++) {
			String[] substr = arStr[i].split("=");
			if( substr.length == 1 )
				params.put( substr[0], "" );
			else if( substr.length == 2 )
				params.put(substr[0], substr[1]);
		}

		return params;
	}
	
	/**
	 * get historyToken by itself
	 * 
	 * like domain.tld#[historyToken]?params=1
	 *  
	 * @param historyToken The entire history token string, with parameters
	 * @return The token without the parameters
	 */
	public static String getHistoryToken(String historyToken) {

		if (!historyToken.contains("?")) {
			return historyToken;
		}

		//get just the historyToken/anchor tag
		String[] arStr = historyToken.split("\\?");
		historyToken = arStr[0];

		return historyToken;
	}


	/**
	 * Builds an history token given the basic token and the parameters to add
	 * 
	 * @param stateToken The basic token
	 * @param params The parameters to append
	 * @return The fuilly built token
	 */
	public static String buildHistoryToken(
			String stateToken,
			HashMap<String, String> params) {
		
		if( params == null ) return stateToken;
		String result = new String( stateToken );
		boolean first = true;
		for (Iterator<Entry<String,String>> iterator = params.entrySet().iterator(); iterator.hasNext();) {
			if( first )
				result += "?";
			else
				result += "&";	
			first = false;
			
			Entry<String,String> entry =  iterator.next();
			result += entry.getKey() + "=" + entry.getValue();
		}
				
		return result;
	}
	
}
